<template>
  <div id="app">
    <div class="container">
      <h1>智能数据标注工具</h1>
      
      <!-- 工具栏 -->
      <div class="toolbar">
        <button @click="addLabel" class="btn btn-primary">添加标签</button>
        <button @click="deleteSelected" class="btn btn-danger">删除选中</button>
        <button @click="saveAnnotations" class="btn btn-success">保存标注</button>
        <button @click="loadSampleImage" class="btn btn-secondary">加载示例图片</button>
        <button @click="uploadImage" class="btn btn-info">上传图片</button>
        <button @click="autoAnnotate" class="btn btn-ai" :disabled="isAutoAnnotating">
          {{ isAutoAnnotating ? 'AI标注中...' : 'AI自动标注' }}
        </button>
        
        <div class="tools">
          <label>
            <input type="radio" v-model="currentTool" value="rect"> 矩形框
          </label>
          <label>
            <input type="radio" v-model="currentTool" value="polygon"> 多边形
          </label>
        </div>
      </div>

      <!-- AI设置面板 -->
      <div class="ai-settings" v-if="showAISettings">
        <h4>AI标注设置</h4>
        <div class="setting-group">
          <label>
            <input type="checkbox" v-model="aiSettings.detectText"> 检测文字
          </label>
          <label>
            <input type="checkbox" v-model="aiSettings.detectObjects"> 检测物体
          </label>
          <label>
            <input type="checkbox" v-model="aiSettings.detectFaces"> 检测人脸
          </label>
        </div>
        <div class="setting-group">
          <label>置信度阈值: {{ aiSettings.confidenceThreshold }}</label>
          <input 
            type="range" 
            v-model="aiSettings.confidenceThreshold" 
            min="0.1" 
            max="1" 
            step="0.1"
          >
        </div>
      </div>

      <!-- 标注区域 -->
      <div class="annotation-area">
        <!-- 图片显示区域 -->
        <div class="image-container" ref="imageContainer">
          <img 
            v-if="currentImage" 
            :src="currentImage" 
            alt="标注图片"
            @load="onImageLoad"
            ref="imageElement"
            @mousedown="startDrawing"
            @mousemove="drawing"
            @mouseup="stopDrawing"
          />
          
          <!-- 标注框 -->
          <div 
            v-for="(annotation, index) in annotations" 
            :key="index"
            class="annotation-box"
            :class="{ 
              selected: selectedAnnotation === index,
              ai: annotation.source === 'ai'
            }"
            :style="getAnnotationStyle(annotation)"
            @mousedown="selectAnnotation(index, $event)"
          >
            <div class="annotation-label">
              {{ annotation.label }}
              <span v-if="annotation.confidence" class="confidence">
                {{ (annotation.confidence * 100).toFixed(1) }}%
              </span>
            </div>
          </div>

          <!-- 绘制中的临时框 -->
          <div 
            v-if="isDrawing && currentTool === 'rect'"
            class="temp-box"
            :style="getTempBoxStyle()"
          ></div>
        </div>

        <!-- 标注列表 -->
        <div class="annotation-list">
          <h3>标注列表 ({{ annotations.length }})</h3>
          <div class="list-controls">
            <button @click="toggleAISettings" class="btn btn-sm">
              {{ showAISettings ? '隐藏AI设置' : '显示AI设置' }}
            </button>
            <button @click="clearAllAnnotations" class="btn btn-sm btn-danger">清空所有</button>
          </div>
          <div 
            v-for="(annotation, index) in annotations" 
            :key="index"
            class="annotation-item"
            :class="{ 
              active: selectedAnnotation === index,
              ai: annotation.source === 'ai'
            }"
            @click="selectAnnotation(index)"
          >
            <span class="label-text">
              {{ annotation.label }}
              <span v-if="annotation.confidence" class="confidence-badge">
                {{ (annotation.confidence * 100).toFixed(0) }}%
              </span>
            </span>
            <div class="item-actions">
              <span class="source-tag" v-if="annotation.source === 'ai'">AI</span>
              <button @click.stop="deleteAnnotation(index)" class="delete-btn">×</button>
            </div>
          </div>
          <div v-if="annotations.length === 0" class="empty-state">
            暂无标注，点击"AI自动标注"或手动绘制
          </div>
        </div>
      </div>

      <!-- 标签编辑模态框 -->
      <div v-if="showLabelModal" class="modal">
        <div class="modal-content">
          <h3>编辑标签</h3>
          <input 
            v-model="editingLabel" 
            @keyup.enter="confirmLabel"
            placeholder="输入标签名称"
            ref="labelInput"
          />
          <div class="modal-actions">
            <button @click="confirmLabel" class="btn btn-primary">确认</button>
            <button @click="cancelLabel" class="btn btn-secondary">取消</button>
          </div>
        </div>
      </div>

      <!-- AI进度模态框 -->
      <div v-if="showAIProgress" class="modal">
        <div class="modal-content">
          <h3>AI标注中</h3>
          <div class="progress-container">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: aiProgress + '%' }"></div>
            </div>
            <div class="progress-text">{{ aiProgress }}%</div>
          </div>
          <p>正在分析图片内容，请稍候...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      currentImage: null,
      annotations: [],
      selectedAnnotation: null,
      currentTool: 'rect',
      isDrawing: false,
      startX: 0,
      startY: 0,
      currentX: 0,
      currentY: 0,
      showLabelModal: false,
      editingLabel: '',
      imageScale: 1,
      imageOffset: { x: 0, y: 0 },
      naturalWidth: 0,
      naturalHeight: 0,
      
      // AI相关状态
      isAutoAnnotating: false,
      showAISettings: true,
      showAIProgress: false,
      aiProgress: 0,
      aiSettings: {
        detectText: true,
        detectObjects: true,
        detectFaces: false,
        confidenceThreshold: 0.5
      },
      
      pendingAnnotation: null
    }
  },
  methods: {
    // 加载示例图片
    loadSampleImage() {
      const sampleImages = [
        'https://images.unsplash.com/photo-1541963463532-d68292c34b19?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80',
        'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80',
        'https://images.unsplash.com/photo-1452587925148-ce544e77e70d?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80'
      ];
      
      const randomImage = sampleImages[Math.floor(Math.random() * sampleImages.length)];
      this.currentImage = randomImage;
      this.annotations = [];
      this.selectedAnnotation = null;
    },

    // 上传图片
    uploadImage() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (event) => {
            this.currentImage = event.target.result;
            this.annotations = [];
            this.selectedAnnotation = null;
          };
          reader.readAsDataURL(file);
        }
      };
      input.click();
    },

    // 图片加载完成
    onImageLoad() {
      const img = this.$refs.imageElement;
      this.naturalWidth = img.naturalWidth;
      this.naturalHeight = img.naturalHeight;
      this.calculateImageScale();
    },

    // 缩放比例
    calculateImageScale() {
      const img = this.$refs.imageElement;
      const container = this.$refs.imageContainer;
      if (img && container) {
        const containerWidth = container.clientWidth;
        const imgWidth = img.naturalWidth;
        this.imageScale = containerWidth / imgWidth;
        
        // 计算图片
        this.imageOffset.x = (containerWidth - img.width) / 2;
        this.imageOffset.y = (container.clientHeight - img.height) / 2;
      }
    },

    // 绘制
    startDrawing(event) {
      if (this.currentTool === 'rect') {
        const rect = this.$refs.imageContainer.getBoundingClientRect();
        this.startX = event.clientX - rect.left;
        this.startY = event.clientY - rect.top;
        this.currentX = this.startX;
        this.currentY = this.startY;
        this.isDrawing = true;
      }
    },
    drawing(event) {
      if (this.isDrawing && this.currentTool === 'rect') {
        const rect = this.$refs.imageContainer.getBoundingClientRect();
        this.currentX = event.clientX - rect.left;
        this.currentY = event.clientY - rect.top;
      }
    },
    stopDrawing() {
      if (this.isDrawing && this.currentTool === 'rect') {
        this.isDrawing = false;
        
        
        const width = Math.abs(this.currentX - this.startX);
        const height = Math.abs(this.currentY - this.startY);
        
        if (width > 10 && height > 10) {
          this.showLabelModal = true;
          this.editingLabel = `标签${this.annotations.length + 1}`;
          
          
          this.pendingAnnotation = {
            x: Math.min(this.startX, this.currentX),
            y: Math.min(this.startY, this.currentY),
            width: width,
            height: height,
            label: '',
            source: 'manual'
          };
          
          this.$nextTick(() => {
            this.$refs.labelInput && this.$refs.labelInput.focus();
          });
        }
      }
    },

    // 获取标注框
    getAnnotationStyle(annotation) {
      return {
        left: annotation.x + 'px',
        top: annotation.y + 'px',
        width: annotation.width + 'px',
        height: annotation.height + 'px'
      };
    },

    // 获取临时框
    getTempBoxStyle() {
      return {
        left: Math.min(this.startX, this.currentX) + 'px',
        top: Math.min(this.startY, this.currentY) + 'px',
        width: Math.abs(this.currentX - this.startX) + 'px',
        height: Math.abs(this.currentY - this.startY) + 'px'
      };
    },

    // 选择标注
    selectAnnotation(index, event) {
      if (event) {
        event.stopPropagation();
      }
      this.selectedAnnotation = index;
    },

    // 添加标签
    addLabel() {
      if (this.selectedAnnotation !== null) {
        this.showLabelModal = true;
        this.editingLabel = this.annotations[this.selectedAnnotation].label;
        this.$nextTick(() => {
          this.$refs.labelInput && this.$refs.labelInput.focus();
        });
      }
    },

    // 确认标签
    confirmLabel() {
      if (this.pendingAnnotation) {
        // 新标注
        this.pendingAnnotation.label = this.editingLabel;
        this.annotations.push({ ...this.pendingAnnotation });
        this.pendingAnnotation = null;
      } else if (this.selectedAnnotation !== null) {
        // 编辑现有标注
        this.annotations[this.selectedAnnotation].label = this.editingLabel;
      }
      
      this.showLabelModal = false;
      this.editingLabel = '';
    },

    // 取消标签编辑
    cancelLabel() {
      this.showLabelModal = false;
      this.editingLabel = '';
      this.pendingAnnotation = null;
    },

    // 删除选中标注
    deleteSelected() {
      if (this.selectedAnnotation !== null) {
        this.annotations.splice(this.selectedAnnotation, 1);
        this.selectedAnnotation = null;
      }
    },

    // 删除指定标注
    deleteAnnotation(index) {
      this.annotations.splice(index, 1);
      if (this.selectedAnnotation === index) {
        this.selectedAnnotation = null;
      }
    },

    // 清空所有标注
    clearAllAnnotations() {
      if (confirm('确定要清空所有标注吗？')) {
        this.annotations = [];
        this.selectedAnnotation = null;
      }
    },

    // 保存标注
    saveAnnotations() {
      if (this.annotations.length === 0) {
        alert('没有标注数据可保存');
        return;
      }
      
      const data = {
        image: this.currentImage,
        annotations: this.annotations,
        timestamp: new Date().toISOString(),
        imageInfo: {
          naturalWidth: this.naturalWidth,
          naturalHeight: this.naturalHeight
        }
      };
      
      const dataStr = JSON.stringify(data, null, 2);
      const blob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'annotations.json';
      a.click();
      URL.revokeObjectURL(url);
      
      alert(`已保存 ${this.annotations.length} 个标注`);
    },


    toggleAISettings() {
      this.showAISettings = !this.showAISettings;
    },


    async autoAnnotate() {
      if (!this.currentImage) {
        alert('请先加载图片');
        return;
      }

      this.isAutoAnnotating = true;
      this.showAIProgress = true;
      this.aiProgress = 0;

      try {
        const progressInterval = setInterval(() => {
          this.aiProgress += Math.random() * 15;
          if (this.aiProgress >= 100) {
            clearInterval(progressInterval);
            this.aiProgress = 100;
            
            // 延迟一下显示结果
            setTimeout(() => {
              this.generateAIAnnotations();
              this.showAIProgress = false;
              this.isAutoAnnotating = false;
            }, 500);
          }
        }, 200);

      } catch (error) {
        console.error('AI标注失败:', error);
        alert('AI标注失败，请重试');
        this.showAIProgress = false;
        this.isAutoAnnotating = false;
      }
    },

    // 模拟AI接口返回
    generateAIAnnotations() {
      this.annotations = [];
      const aiAnnotations = [];
      if (this.aiSettings.detectText) {
        aiAnnotations.push(
          {
            x: this.imageOffset.x + 50,
            y: this.imageOffset.y + 30,
            width: 120,
            height: 25,
            label: '文字区域',
            confidence: 0.87,
            source: 'ai',
            type: 'text'
          },
          {
            x: this.imageOffset.x + 200,
            y: this.imageOffset.y + 80,
            width: 80,
            height: 20,
            label: '标题',
            confidence: 0.92,
            source: 'ai',
            type: 'text'
          }
        );
      }
      if (this.aiSettings.detectObjects) {
        aiAnnotations.push(
          {
            x: this.imageOffset.x + 150,
            y: this.imageOffset.y + 150,
            width: 100,
            height: 120,
            label: '人物',
            confidence: 0.78,
            source: 'ai',
            type: 'object'
          },
          {
            x: this.imageOffset.x + 300,
            y: this.imageOffset.y + 200,
            width: 80,
            height: 60,
            label: '车辆',
            confidence: 0.85,
            source: 'ai',
            type: 'object'
          },
          {
            x: this.imageOffset.x + 400,
            y: this.imageOffset.y + 100,
            width: 60,
            height: 90,
            label: '建筑',
            confidence: 0.91,
            source: 'ai',
            type: 'object'
          }
        );
      }
      const filteredAnnotations = aiAnnotations.filter(
        annotation => annotation.confidence >= this.aiSettings.confidenceThreshold
      );
      this.annotations = filteredAnnotations;
      
      alert(`AI自动标注完成，共检测到 ${filteredAnnotations.length} 个目标`);
    },

    // 需要一个真实AI接口
    async callRealAIApi() {
      return [];
    }
  },
  mounted() {
    this.loadSampleImage();
    window.addEventListener('resize', this.calculateImageScale);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.calculateImageScale);
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Arial', sans-serif;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background-color: #c82333;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background-color: #218838;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #545b62;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover:not(:disabled) {
  background-color: #138496;
}

.btn-ai {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: bold;
}

.btn-ai:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.tools {
  display: flex;
  gap: 15px;
  margin-left: auto;
}

.tools label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.ai-settings {
  background: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.ai-settings h4 {
  margin-bottom: 10px;
  color: #333;
}

.setting-group {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.setting-group label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.setting-group input[type="range"] {
  width: 150px;
}

.annotation-area {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
}

.image-container {
  position: relative;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  min-height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-container img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.annotation-box {
  position: absolute;
  border: 2px solid #007bff;
  background-color: rgba(0, 123, 255, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.annotation-box:hover {
  background-color: rgba(0, 123, 255, 0.2);
}

.annotation-box.selected {
  border-color: #ff4757;
  background-color: rgba(255, 71, 87, 0.2);
  z-index: 10;
}

.annotation-box.ai {
  border-color: #764ba2;
  background-color: rgba(118, 75, 162, 0.1);
}

.annotation-box.ai.selected {
  border-color: #ff4757;
  background-color: rgba(255, 71, 87, 0.2);
}

.annotation-label {
  position: absolute;
  top: -25px;
  left: 0;
  background: #007bff;
  color: white;
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 3px;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 4px;
}

.annotation-box.selected .annotation-label {
  background: #ff4757;
}

.annotation-box.ai .annotation-label {
  background: #764ba2;
}

.confidence {
  font-size: 10px;
  opacity: 0.8;
}

.temp-box {
  position: absolute;
  border: 2px dashed #007bff;
  background-color: rgba(0, 123, 255, 0.1);
}

.annotation-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  max-height: 600px;
  overflow-y: auto;
}

.annotation-list h3 {
  margin-bottom: 15px;
  color: #333;
}

.list-controls {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
}

.annotation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.annotation-item:hover {
  background-color: #f8f9fa;
}

.annotation-item.active {
  background-color: #e7f3ff;
  border-color: #007bff;
}

.annotation-item.ai {
  border-left: 3px solid #764ba2;
}

.annotation-item.ai.active {
  background-color: #f0e6ff;
}

.label-text {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 5px;
}

.confidence-badge {
  background: #764ba2;
  color: white;
  padding: 1px 4px;
  border-radius: 3px;
  font-size: 10px;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.source-tag {
  background: #764ba2;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
}

.delete-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #dc3545;
  cursor: pointer;
  padding: 0 5px;
}

.delete-btn:hover {
  color: #c82333;
}

.empty-state {
  text-align: center;
  color: #6c757d;
  font-style: italic;
  padding: 20px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  min-width: 300px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.2);
}

.modal-content h3 {
  margin-bottom: 15px;
  color: #333;
}

.modal-content input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.progress-container {
  margin: 20px 0;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background: #e9ecef;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  margin-top: 5px;
  font-weight: bold;
  color: #333;
}

@media (max-width: 768px) {
  .annotation-area {
    grid-template-columns: 1fr;
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .tools {
    margin-left: 0;
    justify-content: center;
  }
  
  .setting-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>